<template>
    <div v-loading="loading" class="app-container documentation-container">
      <el-descriptions v-if="data" title="入职信息" :column="3" border>
        <template slot="extra">
          入职情况：
          <span v-if="data.status == 'waiting'" style="margin-right: 10px">
            <el-button
              type="success"
              @click="operate('success')"
            >审核通过</el-button>
            <el-button type="danger" @click="operate('fail')">审核失败</el-button>
          </span>
          <el-tag v-if="data.status == 'waiting'" type="warning">待审核</el-tag>
          <el-tag v-if="data.status == 'success'" type="success">审核成功</el-tag>
          <el-tag v-if="data.status == 'fail'" type="danger">审核失败</el-tag>
        </template>
        <el-descriptions-item label="姓名">{{
          data.interview?.name
        }}</el-descriptions-item>
        <el-descriptions-item label="身份证">{{
          data.identity_card
        }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ data.email }}</el-descriptions-item>
        <el-descriptions-item label="身高">{{
          data.height
        }}</el-descriptions-item>
        <el-descriptions-item label="体重">{{
          data.weight
        }}</el-descriptions-item>
        <el-descriptions-item label="户口性质">
          {{ data.registered_residence == 1 ? "农村" : "非农村" }}
        </el-descriptions-item>
        <el-descriptions-item label="毕业院校">{{
          data.school?.school_name
        }}</el-descriptions-item>
        <el-descriptions-item label="毕业时间">{{
          data.graduation_at
        }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ data.major }}</el-descriptions-item>
        <el-descriptions-item label="政治面貌">{{
          data.politic?.name
        }}</el-descriptions-item>
        <el-descriptions-item label="银行卡号">{{
          data.bank_card
        }}</el-descriptions-item>
        <el-descriptions-item label="开户行">{{
          data.bank?.bankName
        }}</el-descriptions-item>
        <!-- <el-descriptions-item label="学历">{{ data.education?.name }}</el-descriptions-item> -->
        <el-descriptions-item label="提交时间">{{
          data.created_at
        }}</el-descriptions-item>
        <el-descriptions-item label="社保编号">{{
          data?.social_insurance?.toString() !== "null"
            ? data.social_insurance
            : "未录入"
        }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-bottom: 10px">
        <div class="work-title">
          <table style="width: 100%">
            <tr>
              <td><span>家庭成员</span></td>
            </tr>
          </table>
        </div>
        <el-table :data="family" style="width: 100%">
          <el-table-column prop="member" label="姓名" />
          <el-table-column prop="relationship" label="关系" />
          <el-table-column prop="age" label="年龄" />
          <el-table-column prop="workPlace" label="工作地点" />
          <el-table-column prop="salary" label="收入" />
          <el-table-column prop="politics.label" label="政治面貌" />
        </el-table>
      </div>
      <EntryInfo :data="data.interview" @change="getInterviews()" />
      <el-dialog
        title="提交信息"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="30%"
      >
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="宿舍">
            <el-cascader
              v-model="form.roomID"
              style="width:100%;"
              :options="roomFormatter"
              placeholder="选择宿舍"
            />
          </el-form-item>
          <el-form-item label="培训">
            <el-select v-model="form.needCourse" style="width: 100%;" placeholder="请选择是否需要培训">
              <el-option
                v-for="item in needCourseOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程">
            <el-select v-model="form.courseIDs" multiple style="width: 100%;" placeholder="请选择课程" :disabled="form.needCourse !== 1">
              <el-option
                v-for="item in courseOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :loading="btnLoading"
            @click="post()"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import EntryInfo from '@/components/Entry/Info'
  import { getEntry, examineEntry } from '@/api/entry'
  import { getDormitory } from '@/api/basic'
  import { course } from '@/api/train'
  import { atLeast, isNumber, isObject, last } from '@/utils/kris_utils'
  export default {
    name: 'Documentation',
    components: { EntryInfo },
    data() {
      return {
        data: {},
        loading: false,
        family: [],
        dialogVisible: false,
        courseOptions: [],
        needCourseOptions: [
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ],
        form: {
          roomID: null,
          needCourse: 0,
          courseIDs: []
        },
        btnLoading: false,
        dormitory: []
      }
    },
    computed: {
      roomFormatter() {
        if (!Array.isArray(this.dormitory)) { return [] }
  
        return this.dormitory.map(item => {
          const { address, id, room } = item
  
          let children = []
          let isDisabled = true
  
          if (Array.isArray(room) && room.length > 0) {
            isDisabled = false
            children = room.map(r => {
              const available = r.number - (r.userCompany?.length ?? 0)
              return { label: r.name, value: r.id, disabled: available <= 0 }
            })
          }
          return {
            label: address,
            value: id,
            disabled: isDisabled,
            children
          }
        })
      }
    },
    watch: {
      courseOptions() {
        if (isNumber(this.form.needCourse) && this.form.needCourse === 1) {
          this.$nextTick(this.checkDefaultCourses)
        }
      },
      'form.needCourse': function(needCourse) {
        if (!isNumber(needCourse)) { return }
  
        if (needCourse === 1) {
          this.$nextTick(this.checkDefaultCourses)
        } else {
          this.form.courseIDs = []
        }
      }
    },
    created() {
      this.getEntrys()
      this.getDorm()
      this.getCourses()
    },
    methods: {
      checkDefaultCourses() {
        const selected = [...this.form.courseIDs]
        const defaultCourseIds = this.courseOptions
          .filter(item => item.isDefaultCourse === 1)
          .map(item => item.value)
        const uniqueIds = [...new Set([...defaultCourseIds, ...selected])]
        this.form.courseIDs = uniqueIds
      },
      async getCourses() {
        const params = {
          paginate: 10000
        }
        const result = await course(params)
        this.courseOptions = result.data.map(item => {
          return {
            label: item.title,
            value: item.id,
            isDefaultCourse: item['default']
          }
        })
      },
      getDorm() {
        getDormitory()
          .then((res) => {
            this.dormitory = res.data
          })
          .catch((err) => {})
      },
      // 获取用户信息
      async getEntrys() {
        this.loading = true
        const res = await getEntry(this.$route.params.id)
        console.log(res, 'getEntry')
        this.data = res.data
        this.data.interview.identity_card_reverse =
          res.data.identity_card_reverse
        if (this.$isJSON(this.data.family_situation)) {
          this.family = JSON.parse(this.data.family_situation)
        }
        this.loading = false
      },
      post() {
        this.btnLoading = true
  
        const params = {}
  
        if (Array.isArray(this.form.roomID) && this.form.roomID.length > 0) {
          params['room_id'] = last(this.form.roomID)
        }
  
        if (this.form.needCourse === 1) {
          params['needCourse'] = this.form.needCourse
          params['course_id'] = JSON.stringify(this.form.courseIDs)
        }
        examineEntry({
          agree: 1,
          id: this.data.id,
          // ...(Array.isArray(params) ? params : Object.entries(params))
          ...params
        }).then((res) => {
          console.log(res, 'cg')
          this.getEntrys()
          this.btnLoading = false
          this.dialogVisible = false
        })
          .catch((e) => {
            console.log(e, '报错信息')
            this.btnLoading = false
            const errMsg = e?.response?.data?.message ?? '操作失败'
            this.$message.error(errMsg)
          })
      },
      operate(type) {
        switch (type) {
          case 'success':
            this.dialogVisible = true
            break
          case 'fail':
            this.$prompt(
              `是否拒绝${this.data.interview?.name}的入职申请，拒绝后${this.data?.interview?.name}可重新提交`,
              '拒绝入职申请',
              {
                inputValidator(value) {
                  if (typeof value === 'string' && value.trim() !== '') { return true }
                  return '请输入拒绝理由'
                },
                inputPlaceholder: '请输入拒绝理由',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
              .then(({ value }) => {
                examineEntry({
                  id: this.data.id,
                  agree: 2,
                  fail_reason: value
                }).then((res) => {
                  this.$notify({
                    title: '成功',
                    message: '拒绝成功',
                    type: 'success'
                  })
                  this.getEntrys()
                })
              })
              .catch(() => {})
            break
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    background-color: #fff;
  }
  .work-title {
    font-size: 16px;
    font-weight: bold;
    margin: 20px 0;
  }
  </style>
  
  